{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "318c718d-802e-452e-8779-a60c61057068",
   "metadata": {},
   "source": [
    "<center><img src=\"./image/CLBLOGO.jpg\" alt=\"创乐博\" style=\"width: 300px;\"/></center>\n",
    "\n",
    "# 24.超声波传感器距离检测\n",
    "\n",
    "@－－－－湖南创乐博智能科技有限公司－－－－<br>\n",
    "@  文件名：24.超声波传感器距离检测.py <br>\n",
    "@  版本：V2.0 <br>\n",
    "@  author: zhulin<br>\n",
    "@  说明：超声波传感器距离检测\n",
    "超声波传感器距离检测，通过GPIOZero库的超声波DistanceSensor库直接控制超声波传感器进行距离检测，从而打印在jupyter 界面上！！！！！！<br>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f5f58331-df2f-409c-b08b-1401a5100a80",
   "metadata": {},
   "source": [
    "## 1.导入必要的库文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "24bb5df6-9701-49a1-8df4-dcbd1a87c5fc",
   "metadata": {},
   "outputs": [],
   "source": [
    "from gpiozero import DistanceSensor\n",
    "from time import sleep"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bf81ed90-ea51-4447-b522-85494d089b54",
   "metadata": {},
   "source": [
    "## 2.定义超声波传感器管脚"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "20561d89-e334-41e0-9358-07f9b385ffdd",
   "metadata": {},
   "outputs": [],
   "source": [
    "makerobo_sensor = DistanceSensor(echo=17, trigger=18,max_distance=3, threshold_distance=0.2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "04b01200-b8f4-4906-9fef-ee5921375822",
   "metadata": {},
   "source": [
    "## 3.主程序"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "45e18609-d482-4008-9b7f-64ee3599f522",
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "try:\n",
    "    # 循环函数\n",
    "    while True:\n",
    "        dis = makerobo_sensor.distance * 100  # 测量距离值，并把m单位换成cm单位\n",
    "        print('Distance: {:.2f} cm'.format(dis))  # 以两位小数精度打印距离\n",
    "        sleep(0.3)  # 等待0.3秒再进行下一次测量\n",
    "\n",
    "except KeyboardInterrupt:\n",
    "    # 处理KeyboardInterrupt (Ctrl+C)以正常退出循环\n",
    "    pass"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
